let { projectRootPath } = require("../../../util/index");
let { getNewRouter } = require(`${projectRootPath}/app/index.js`);
let { signToken, verifyToken } = require(
  `${projectRootPath}/util/jwt/index.js`,
);
let app = getNewRouter();
let { admin } = require(`${projectRootPath}/config/index.js`);
let { getUserByUsername, editUserByUuid, getUserByAll } = require(
  `${projectRootPath}/service/user/index.js`,
);
let { getRoleByAll } = require(`${projectRootPath}/service/role/index.js`);
// 系统登陆
app.post("/in", async (req, res) => {
  try {
    let { username, password } = req.body;
    if (username === admin.username && password === admin.password) {
      return res.send({ data: { token: signToken(admin) }, code: 20000 });
    }
    let user = await getUserByUsername(req.body);
    user = user.list[0];
    if (username === user.username && password === user.password) {
      let allRole = await getRoleByAll();
      allRole = allRole.list;
      let userInfo = {
        name: user.name,
        username: user.username,
        password: user.password,
        roleList: JSON.parse(user.roleUuidList).map((roleUuid) => {
          let role = allRole.find((role) => {
            return role.uuid === roleUuid;
          });
          return role.name;
        }),
        avatar: user.avatar,
        datetime: String(new Date().getTime()),
      };
      let token = signToken(userInfo);
      user = {
        ...user,
        token,
      };
      await editUserByUuid(user);
      return res.send({ data: { token }, code: 20000 });
    } else {
      throw new Error("账号密码错误");
    }
  } catch (error) {
    res.send({ data: {}, message: error.message, code: 20001 });
  }
});
// 系统退出
app.post("/out", async (req, res) => {
  try {
    let token = req.body.token;
    let userInfo = verifyToken(token);
    if (userInfo.username === "xiaoli") {
      return res.send({ data: {}, code: 20000 });
    }
    let allUser = await getUserByAll();
    allUser = allUser.list;
    let user = allUser.find((user) => {
      return user.username === userInfo.username;
    });
    if (!user) {
      res.send({ data: {}, message: "无此用户", code: 20001 });
    }
    user.token = "";
    await editUserByUuid(user);
    return res.send({ data: {}, code: 20000 });
  } catch (error) {
    res.send({ data: {}, message: error.message, code: 20001 });
  }
});
// 导出 app
module.exports = app;
